package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.ELogState;
import com.gzhryc.shared_device.base.models.OrderLogContent;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNOrderLog;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNShopOrderLog;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNOrderLogService;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNShopOrderLogService;
import com.gzhryc.shared_device.cdb.code.dao.db.CDBOrderLog;
import com.gzhryc.shared_device.cdb.code.services.CDBOrderLogService;
import com.gzhryc.shared_device.cdcz.code.dao.db.CDCZOrderLog;
import com.gzhryc.shared_device.cdcz.code.services.CDCZOrderLogService;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberBusinessOrder;
import com.gzhryc.shared_device.oem.code.member.services.MemberBusinessOrderService;
import com.gzhryc.shared_device.oem.code.member.services.dto.MemberBusinessOrderSearch;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceClerk;
import com.gzhryc.shared_device.oem.code.place.services.PlaceClerkService;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrderUser;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrderUserProfit;
import com.gzhryc.shared_device.oem.code.profit.service.BusinessOrderUserProfitService;
import com.gzhryc.shared_device.oem.code.profit.service.BusinessOrderUserService;
import com.gzhryc.shared_device.oem.code.profit.service.dto.BusinessOrderUserSearch;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.order.BusinessOrderListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.order.BusinessOrderListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.order.BusinessOrderOperateRecordListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.order.BusinessOrderOperateRecordListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.order.BusinessOrderProfitListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.order.BusinessOrderProfitListResponse;
import com.gzhryc.shared_device.pcl.code.dao.db.PCLOrderLog;
import com.gzhryc.shared_device.pcl.code.services.PCLOrderLogService;

public class BusinessOrderController {

    static Logger log = Logger.getLogger(BusinessOrderController.class);

    @Route(value = "/agent/api/v1/order/list.data")
    public BusinessOrderListResponse listData(HttpServletRequest request) {
        BusinessOrderListResponse apiResp = new BusinessOrderListResponse(ClientAPICodeConstants.NULL_DATA,"暂无数据");
        BusinessOrderListRequest apiReq = WebUtils.getJsonRequest(request, BusinessOrderListRequest.class);
        if (apiReq != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Integer pageNo = apiReq.getBody().getPageNo() == null ? 1 : apiReq.getBody().getPageNo();
                Date currentDate = new Date();
                if(StringTools.isNotBlank(apiReq.getBody().getYear())){
                    try {
                        currentDate = DateUtils.parseDate(apiReq.getBody().getYear(),"yyyy");
                    } catch (ParseException e) {
                        log.error(e.getMessage(),e);
                    }
                }
                
                if(ERoleType.Clerk.index().equals(loginUser.getRoleType())) {
                	//根据网点Id查询
                	List<PlaceClerk> placeClerkList = PlaceClerkService.self().findByUserKeys(loginUser.getId(), loginUser.getParentId());
                	if(placeClerkList != null && placeClerkList.size() > 0) {
                		MemberBusinessOrderSearch search = new MemberBusinessOrderSearch();
                		search.setPlaceIds(new ArrayList<>());
                		for(PlaceClerk placeClerk : placeClerkList) {
                			search.getPlaceIds().add(placeClerk.getPlaceId());
                		}
                		
                		List<MemberBusinessOrder> memberBusinessOrderList = MemberBusinessOrderService.self(currentDate).findBySearch(search, pageNo,WebConstants.PAGE_LIMIT);
	                    if(memberBusinessOrderList != null && memberBusinessOrderList.size() > 0) {
	                        apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
	                        apiResp.getBody().setItems(new ArrayList<>());
	                        for (MemberBusinessOrder businessOrder : memberBusinessOrderList){
	                            BusinessOrderListResponse.BusinessOrderItem item = ClassTools.copy(new BusinessOrderListResponse.BusinessOrderItem(),businessOrder);
	                            item.setAreaName(businessOrder.getAreaName());
	                            item.setStateName(businessOrder.getStateName());
	                            item.setMoneyStr(businessOrder.getMoneyStr());
	                            apiResp.getBody().getItems().add(item);
	                        }
	                    }
                	}
                }else {
	                BusinessOrderUserSearch search = new BusinessOrderUserSearch();
	                if(ERoleType.Agent.index().equals(loginUser.getRoleType())) {
	                	search.setPlaceUserId(loginUser.getId());
	                }else if(loginUser.getParentId() != null){
	                	search.setPlaceUserId(loginUser.getParentId());
	                	search.setUserId(loginUser.getId());
	                }else {
	                	apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
	                    return apiResp;
	                }
	                search.setDeviceFunCode(apiReq.getBody().getDeviceFunCode());
	                search.setState(apiReq.getBody().getState());
	                search.setTrim(apiReq.getBody().getTrim());
	                List<BusinessOrderUser> userBusinessOrderList = BusinessOrderUserService.self(currentDate).findBySearch(search,pageNo,WebConstants.PAGE_LIMIT);
	                if(userBusinessOrderList != null && userBusinessOrderList.size() > 0){
	                    List<String> tradeNoList = new ArrayList<>();
	                    for(BusinessOrderUser order : userBusinessOrderList){
	                        tradeNoList.add(order.getTradeNo());
	                    }
	
	                    List<MemberBusinessOrder> memberBusinessOrderList = MemberBusinessOrderService.self(currentDate).findByTradeNoList(tradeNoList);
	                    if(memberBusinessOrderList != null && memberBusinessOrderList.size() > 0) {
	                        apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
	                        apiResp.getBody().setItems(new ArrayList<>());
	                        for (MemberBusinessOrder businessOrder : memberBusinessOrderList){
	                            BusinessOrderListResponse.BusinessOrderItem item = ClassTools.copy(new BusinessOrderListResponse.BusinessOrderItem(),businessOrder);
	                            item.setAreaName(businessOrder.getAreaName());
	                            item.setStateName(businessOrder.getStateName());
	                            item.setMoneyStr(businessOrder.getMoneyStr());
	                            apiResp.getBody().getItems().add(item);
	                        }
	                    }
	                }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/order/operate_record/list.data")
    public BusinessOrderOperateRecordListResponse operateRecordListData(HttpServletRequest request) {
        BusinessOrderOperateRecordListResponse apiResp = new BusinessOrderOperateRecordListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        BusinessOrderOperateRecordListRequest apiReq = WebUtils.getJsonRequest(request, BusinessOrderOperateRecordListRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getTradeNo())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Date createDate = new Date();
                if (StringTools.isNotBlank(apiReq.getBody().getCreateDate())) {
                    try {
                        createDate = DateUtils.parseDate(apiReq.getBody().getCreateDate(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd");
                    } catch (ParseException e) {
                        log.error(e.getMessage(), e);
                    }
                }
                
                Long userId = loginUser.getId();

                if(ERoleType.Clerk.index().equals(loginUser.getRoleType())) {
                	//如果是店员，则检查商户有没有权限控制该订单
                	userId = loginUser.getParentId();
                }
                
                //权限控制
                BusinessOrderUser businessOrderUser = BusinessOrderUserService.self(createDate).getByKeys(apiReq.getBody().getTradeNo(), userId);
                if (businessOrderUser == null) {
                    apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
                    return apiResp;
                }

                String businessType = apiReq.getBody().getBusinessType();
                if (StringTools.isBlank(businessType)) {
                    MemberBusinessOrder memberBusinessOrder = MemberBusinessOrderService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                    if(memberBusinessOrder != null){
                    	//如果是店员，还需要检查是否有网点的权限
                    	if(ERoleType.Clerk.index().equals(loginUser.getRoleType())) {
                    		PlaceClerk placeClerk = PlaceClerkService.self().getByKeys(memberBusinessOrder.getPlaceId(),loginUser.getId());
                    		if(placeClerk == null) {
                    			 apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
                                 return apiResp;
                    		}
                    	}
                    	
                        businessType = memberBusinessOrder.getBusinessType();
                    }else{
                        apiResp.setMsg("未找到订单信息");
                        return apiResp;
                    }
                }

                OrderLogContent orderLogContent = null;
                if (EBusinessType.CDCZ.index().equals(businessType)) {
                    CDCZOrderLog orderLog = CDCZOrderLogService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                    if (orderLog != null && StringTools.isNotBlank(orderLog.getContent())) {
                        orderLogContent = JsonTools.fromJson(orderLog.getContent(), OrderLogContent.class);
                    }
                } else if (EBusinessType.CDB.index().equals(businessType)) {
                    CDBOrderLog orderLog = CDBOrderLogService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                    if (orderLog != null && StringTools.isNotBlank(orderLog.getContent())) {
                        orderLogContent = JsonTools.fromJson(orderLog.getContent(), OrderLogContent.class);
                    }
                } else if (EBusinessType.BXSCN.index().equals(businessType)) {
                    BXSCNOrderLog orderLog = BXSCNOrderLogService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                    if (orderLog != null && StringTools.isNotBlank(orderLog.getContent())) {
                        orderLogContent = JsonTools.fromJson(orderLog.getContent(), OrderLogContent.class);
                    }
                }else if (EBusinessType.BXSCN_SHOP.index().equals(businessType)) {
                    BXSCNShopOrderLog orderLog = BXSCNShopOrderLogService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                    if (orderLog != null && StringTools.isNotBlank(orderLog.getContent())) {
                        orderLogContent = JsonTools.fromJson(orderLog.getContent(), OrderLogContent.class);
                    }
                }else if (EBusinessType.PCL.index().equals(businessType)) {
                    PCLOrderLog orderLog = PCLOrderLogService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                    if (orderLog != null && StringTools.isNotBlank(orderLog.getContent())) {
                        orderLogContent = JsonTools.fromJson(orderLog.getContent(), OrderLogContent.class);
                    }
                }

                if (orderLogContent != null && orderLogContent.getItems() != null && orderLogContent.getItems().size() > 0) {
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setItems(new ArrayList<>());
                    LinkedHashMap<String,List<BusinessOrderOperateRecordListResponse.Item>> map = new LinkedHashMap<>();

                    for (OrderLogContent.LogItem logItem : orderLogContent.getItems()) {
                        BusinessOrderOperateRecordListResponse.Item item = new BusinessOrderOperateRecordListResponse.Item();
                        String dateStr = DateFormatUtils.format(logItem.getCreateDate(),"yyyy-MM-dd");

                        List<BusinessOrderOperateRecordListResponse.Item> items = map.get(dateStr);
                        if(items == null){
                            items = new ArrayList<>();
                            map.put(dateStr,items);
                        }

                        item.setTimeStr(DateFormatUtils.format(logItem.getCreateDate(),"HH:mm:ss"));
                        item.setContent(logItem.getContent());
                        item.setState(logItem.getState());
                        item.setStateName(ELogState.note(logItem.getState()));
                        item.setErrorsMsg(logItem.getErrorMsg());
                        items.add(item);
                    }

                    for(String dateStr : map.keySet()){
                        BusinessOrderOperateRecordListResponse.DateItem item = new BusinessOrderOperateRecordListResponse.DateItem();
                        item.setDateStr(dateStr);
                        item.setItems(map.get(dateStr));
                        apiResp.getBody().getItems().add(item);
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/order/profit/list.data")
    public BusinessOrderProfitListResponse profitListData(HttpServletRequest request) {
    	BusinessOrderProfitListResponse apiResp = new BusinessOrderProfitListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
    	BusinessOrderProfitListRequest apiReq = WebUtils.getJsonRequest(request, BusinessOrderProfitListRequest.class);
         if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getTradeNo())) {
             LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
             if (loginUser != null) {
                 Date createDate = new Date();
                 if (StringTools.isNotBlank(apiReq.getBody().getCreateDate())) {
                     try {
                         createDate = DateUtils.parseDate(apiReq.getBody().getCreateDate(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd");
                     } catch (ParseException e) {
                         log.error(e.getMessage(), e);
                     }
                 }

                 if(ERoleType.Agent.index().equals(loginUser.getRoleType()) || ERoleType.Partner.index().equals(loginUser.getRoleType())
                		 || ERoleType.Merchant.index().equals(loginUser.getRoleType())) {
                	 Long userId = loginUser.getId();
                	 //权限控制
                     BusinessOrderUser businessOrderUser = BusinessOrderUserService.self(createDate).getByKeys(apiReq.getBody().getTradeNo(), userId);
                     if (businessOrderUser == null) {
                         apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
                         return apiResp;
                     }
                     
                     List<BusinessOrderUserProfit> userProfitList = BusinessOrderUserProfitService.self(createDate).findByTradeNo(apiReq.getBody().getTradeNo());
                     if(userProfitList != null && userProfitList.size() > 0) {
                    	 apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    	 apiResp.getBody().setItems(new ArrayList<>());
                    	 for(BusinessOrderUserProfit userProfit : userProfitList) {
                    		 BusinessOrderProfitListResponse.UserItem item = new BusinessOrderProfitListResponse.UserItem();
                    		 item.setUserId(userProfit.getUserId());
                    		 item.setUserName(userProfit.getName());
                    		 item.setRoleType(userProfit.getRoleType());
                    		 item.setRoleTypeName(userProfit.getRoleTypeName());
                    		 item.setIncomeRatio(userProfit.getIncomeRatio());
                    		 item.setMoneyStr(userProfit.getMoneyStr());
                    		 item.setCreateDate(userProfit.getCreateDate());
                    		 apiResp.getBody().getItems().add(item);
                    	 }
                     }
                 }else {
                	 apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
                     return apiResp;
                 }
                 
                 String businessType = apiReq.getBody().getBusinessType();
                 if (StringTools.isBlank(businessType)) {
                     MemberBusinessOrder memberBusinessOrder = MemberBusinessOrderService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                     if(memberBusinessOrder != null){
                     	//如果是店员，还需要检查是否有网点的权限
                     	if(ERoleType.Clerk.index().equals(loginUser.getRoleType())) {
                     		PlaceClerk placeClerk = PlaceClerkService.self().getByKeys(memberBusinessOrder.getPlaceId(),loginUser.getId());
                     		if(placeClerk == null) {
                     			 apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
                                  return apiResp;
                     		}
                     	}
                     	
                         businessType = memberBusinessOrder.getBusinessType();
                     }else{
                         apiResp.setMsg("未找到订单信息");
                         return apiResp;
                     }
                 }
             }
         }
         return apiResp;
    }
}
